import os
import subprocess
import glob
from shutil import copyfile

vpath = '#third_party/thrift-0.8.0'
env = DefaultEnvironment()

thrift_exe = '#build/bin/thrift.exe'
thritf_lib = '#build/lib/thrift.lib'
thriftasio_lib = '#build/lib/thriftasio.lib'

abs_vpath = Dir(vpath).abspath

msbuild = os.environ['MSBUILD']

def build_thrift_exe(target, source, env):
    subprocess.call([msbuild, 'compiler.vcxproj', '/p:Configuration=' + env['VS_BUILDMODE'], '/p:Platform=x64', '/p:PlatformToolset=v140'], cwd=Dir(vpath + '/compiler/cpp').abspath)
    copyfile(File(vpath + '/compiler/cpp/x64/' + env['VS_BUILDMODE'] + '/thrift.exe').abspath, File(thrift_exe).abspath)

def build_thrift_libs(target,source,env):
    subprocess.call([msbuild, 'thrift.sln', '/p:Configuration=' + env['VS_BUILDMODE'], '/p:Platform=x64', '/p:PlatformToolset=v140'], cwd=Dir(vpath + '/lib/cpp').abspath)
    copyfile(File(vpath + '/lib/cpp/x64/' + env['VS_BUILDMODE'] + '/libthrift.lib').abspath, File(thritf_lib).abspath)
    copyfile(File(vpath + '/lib/cpp/x64/' + env['VS_BUILDMODE'] + '/libthriftnb.lib').abspath, File(thriftasio_lib).abspath)

thrift_libs = [thritf_lib, thriftasio_lib]

env.Command(thrift_exe, Dir(vpath), build_thrift_exe)
env.Command(thrift_libs, Dir(vpath), build_thrift_libs)


headerfiles =  glob.glob(abs_vpath + r'\lib\cpp\src\protocol\*.h')
for hf in headerfiles:
    env.Install('#build/include/thrift/protocol', hf)

headerfiles =  glob.glob(abs_vpath + r'\lib\cpp\src\protocol\*.tcc')
for hf in headerfiles:
    env.Install('#build/include/thrift/protocol', hf)

headerfiles =  glob.glob(abs_vpath + r'\lib\cpp\src\windows\*.h')
for hf in headerfiles:
    env.Install('#build/include/thrift/windows', hf)

headerfiles =  glob.glob(abs_vpath + r'\lib\cpp\src\transport\*.h')
for hf in headerfiles:
    env.Install('#build/include/thrift/transport', hf)

headerfiles =  glob.glob(abs_vpath + r'\lib\cpp\src\async\*.h')
for hf in headerfiles:
    env.Install('#build/include/thrift/async', hf)

headerfiles =  glob.glob(abs_vpath + r'\lib\cpp\src\concurrency\*.h')
for hf in headerfiles:
    env.Install('#build/include/thrift/concurrency', hf)

headerfiles =  glob.glob(abs_vpath + r'\lib\cpp\src\processor\*.h')
for hf in headerfiles:
    env.Install('#build/include/thrift/processor', hf)

headerfiles =  glob.glob(abs_vpath + r'\lib\cpp\src\server\*.h')
for hf in headerfiles:
    env.Install('#build/include/thrift/server', hf)

headerfiles =  glob.glob(abs_vpath + r'\lib\cpp\src\*.h')
for hf in headerfiles:
    env.Install('#build/include/thrift', hf)
